#!/bin/env python3
# -*- coding:utf-8 -*-
"""
    [模块名]
    Add By : cdj <e4ting@qq.com> 2021-07-14 17:57:18
"""
import json
from flask_restful  import Resource
from flask          import redirect,request,make_response

from urllib.parse   import urlparse

from e4ting         import util,log
from core.cache     import RoomCache
from models.mysqls  import db,ModelRoom
from core.game.room import Room
# from e4ting.task   import Anon

# from core.webhook.events import EventBaitPot
# from core.webhook.hooks  import HookSender

class WebRoom(Resource):
    """ 房间 """

    def is_room_exists(self, uid):
        return db.session.query(ModelRoom).filter(ModelRoom.id==uid).first()

    def get(self, id=None):
        """ 单个房间 """
        if not id:
            return ApiErr("房间ID不对", code=400)
        cache = RoomCache(id)
        if not cache.exists():
            return ApiErr("房间不存在", code=404)
        data = cache.get()
        data["players"] = json.loads(data["players"])
        data["visists"] = json.loads(data["visists"])
        game = json.loads(data["game"])
        data["commons"] = game["rounds"][-1]["cards"]
        data["dealer"]  = {"name": "荷官", "btn": data["btn"]}
        return ApiOK(data)

    def post(self, id=None):
        """ 修改房间 """
        if not id:
            return ApiErr("房间ID不对", code=400)
        if not self.is_room_exists(id):
            return ApiErr("房间不存在", code=404)
        # 创建座位
        room = Room(uid=id)
        room.create_seats()
        return ApiOK({})

    def delete(self, id=None):
        """ 删除房间 """
        if not id:
            return ApiErr("房间ID不对", code=400)

        if not self.is_room_exists(id):
            return ApiErr("房间不存在", code=404)
        Room(uid=id)._quit()
        # if not item.exists():
        #     return ApiErr("房间不存在", code=404)
        db.session.query(ModelRoom).filter(ModelRoom.id==id).update({ModelRoom.removed: True})
        db.session.commit()
        return ApiOK(f"房间已删除")

    def put(self, id=None):
        """ 创建房间 """
        name    = request.json.get("name")
        tactics = request.json.get("tactics")

        if not name:
            return ApiErr("房间名不对", code=400)
        # 谁创建的房间
        # who
        # name = request.get("name")

        # item = ModelRoom(id=RoomCache.game, name=name, detail="玩家创建房间 {}".format(util.now()))
        # db.session.add(item)
        # db.session.commit()

        # # cache = RoomCache(item.id)
        # # cache.set(name=name, tactics=tactics)

        # return ApiOK({
        #         "id"   : item.id,
        #         "name" : item.name,
        #         "detail":item.detail,
        #     })

        return ApiOK({
                "detail"   : "暂不真的创建房间",
            })
